package com.hankol.message.bean;

import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import io.rong.common.ParcelUtils
import io.rong.common.RLog
import io.rong.imlib.MessageTag
import io.rong.imlib.model.MessageContent
import io.rong.imlib.model.UserInfo
import org.json.JSONException
import org.json.JSONObject
import java.io.UnsupportedEncodingException

/** 好友关系.
 * 【TA不是好友，不能进行聊天  查看】
【由于对方没有关注你，限制发送3条消息】
【你没有关注TA，不能进行聊天 一键关注】
 *
 *
 *
 * */
@MessageTag(value = "HK:FriendStateNotice", flag = MessageTag.ISPERSISTED)
class FriendStateMessage : MessageContent {
    //* 0=没关系
    //* 1=自己
    //* 2=我关注了他
    //* 3=他关注了我
    //* 4=互相关注
    var type: Int = 0

    constructor() {}
    constructor(type: Int) {
        this.type = type
    }

    companion object {
        private val TAG = "DynamicCardMessage"

        fun obtain(type: Int): FriendStateMessage {
            return FriendStateMessage(type)
        }

        @JvmField
        val CREATOR: Parcelable.Creator<FriendStateMessage> = object : Parcelable.Creator<FriendStateMessage> {
            override fun createFromParcel(source: Parcel): FriendStateMessage {
                return FriendStateMessage(source)
            }

            override fun newArray(size: Int): Array<FriendStateMessage?> {
                return arrayOfNulls(size)
            }
        }
    }

    override fun encode(): ByteArray? {
        val jsonObject = JSONObject()
        try {
            jsonObject.put("type", type)
            if (jsonUserInfo != null) {
                jsonObject.putOpt("user", jsonUserInfo)
            }
        } catch (e: Exception) {
        }
        try {
            return jsonObject.toString().toByteArray(charset("UTF-8"))
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        return null
    }

    constructor(data: ByteArray) {
        var jsonStr: String? = null
        try {
            jsonStr = String(data, Charsets.UTF_8)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        try {
            val jsonObj = JSONObject(jsonStr)
            if (jsonObj.has("type")) type = jsonObj.optInt("type")
            if (jsonObj.has("user")) userInfo = parseJsonToUserInfo(jsonObj.getJSONObject("user"))
        } catch (e: JSONException) {
            RLog.e(TAG, "JSONException " + e.message)
        }
    }

    constructor(`in`: Parcel) {
        type = `in`.readInt()
        userInfo = ParcelUtils.readFromParcel(`in`, UserInfo::class.java)
    }

    override fun describeContents(): Int {
        return 0
    }

    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeInt(type)
        ParcelUtils.writeToParcel(dest, this.userInfo)
    }
}
